package com.lh.oauth.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import com.lh.entity.OpenUser;
import com.lh.entity.OpenUser.OpenUserType;
import com.lh.oauth.OAuth;
import com.lh.util.Configuration;
import com.lh.util.HttpUtil;

/**
 * @author liuhui
 * @version 1.0
 * @date 2013-4-29 下午2:51:23
 */
@Component
public class QQOAuth implements OAuth {
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	private static final String APP_ID="100432186";
	private static final String KEY= "f76d049bf7a12f76879e43185bf63f99";
	
	private static final String AUTHORIZE_URL = "https://graph.qq.com/oauth2.0/authorize";
	
	private static final String TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
	
	private static final String OPENID_URL = "https://graph.qq.com/oauth2.0/me";

	private static final String USER_INFO_URL = "https://graph.qq.com/user/get_user_info";
	private static final String ADD_SHARE_URL = "https://graph.qq.com/share/add_share";
	
	
	private String callBackUrl = CALLBACK_URL+"/" + OpenUserType.QQ.getValue() ;
	
	@Override
	public String genLoginUrl() {
		StringBuilder queryString =  new StringBuilder();
		queryString.append("response_type=code&client_id=").append(APP_ID).append("&redirect_uri=").append(callBackUrl).append("&state=kaijingbao").append("&scope=add_share");
		return AUTHORIZE_URL + "?" + queryString.toString();
	}

	@Override
	public OpenUser obtainOpenUser(String code) {
		StringBuilder queryString =  new StringBuilder();
		queryString.append("grant_type=authorization_code&client_id=").append(APP_ID).append("&client_secret=").append(KEY).append("&code=").append(code).append("&redirect_uri=").append(callBackUrl);
		String accessTokenString = HttpUtil.get(TOKEN_URL + "?" +queryString.toString());
		String accessToken = null;
		for (String  str : accessTokenString.split("&")) {
			if(str.startsWith("access_token=")){
				accessToken = str.substring(str.indexOf("=") + 1 );
				break;
			}
		}
		if(accessToken == null){
			return null;
		}
		String openidString = HttpUtil.get(OPENID_URL + "?" + "access_token=" + accessToken);
		String openid = ((JSONObject)JSONSerializer.toJSON(openidString.substring(openidString.indexOf("{") , openidString.lastIndexOf("}") + 1 ))).getString("openid");
		
		Map<String, String> ps = new HashMap<String, String>();
		ps.put("access_token", accessToken);
		ps.put("oauth_consumer_key", APP_ID);
		ps.put("openid", openid);
		String userInfoString = HttpUtil.get(USER_INFO_URL , ps);
		JSONObject json = (JSONObject) JSONSerializer.toJSON(userInfoString);
		OpenUser ou = new OpenUser();
		ou.setCreateTime(new Date());
		ou.setNickname(json.getString("nickname"));
		ou.setOpenid(openid);
		ou.setUserInfo(json.toString());
		ou.setType(OpenUserType.QQ.getValue());
		ou.setAccessToken(accessToken);
		return ou ;
	}

	public void shareInfo(OpenUser openUser) {
		Map<String, String> ps = new HashMap<String, String>();
		ps.put("access_token", openUser.getAccessToken());
		ps.put("oauth_consumer_key", APP_ID);
		ps.put("openid", openUser.getOpenid());
		
		ps.put("comment", Configuration.OPEN_LOGIN_SHAREMSG +">>http://www.kaijingbao.com");
		ps.put("summary", "凯晶堡是专业的灯具灯饰商城，主营吸顶灯,吊灯,台灯,壁灯,室外/庭院灯,落地灯,镜前灯, 射灯,筒灯,新奇特/其他,小夜灯/橱柜灯,支架/日光灯等一应俱全");
		ps.put("type", "4");
		ps.put("site", "凯晶堡商城");
		ps.put("fromurl", "http://www.kaijingbao.com");
		ps.put("title", "凯晶堡灯饰照亮生活");
		ps.put("url", "http://www.kaijingbao.com");
		ps.put("images", "http://www.kaijingbao.com/images/logo120x120.jpg");
		String rs = HttpUtil.get(ADD_SHARE_URL , ps);
		logger.info( "qq add share " +(JSONObject.fromObject(rs).getInt("ret") == 0 ? "success" : "fail") );
	}

	
}
